<template>
	<div class="layout-padding">
		<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="auto" v-loading="loading">
			<el-card>
				<template #header>
					<div class="card-header">
						<span>轮播图设置</span>
						<div class="button-box"><el-button type="primary" @click="onSubmit">提交</el-button></div>
					</div>
				</template>
				<el-form-item label="轮播图设置" prop="carousel">
					<div class="carousel-list">
						<div v-for="(item, index) in formData.carousel" :key="index" class="carousel-card">
							<div class="card-header">
								<span class="card-index">轮播图 {{ index + 1 }}</span>
								<el-icon class="delete-btn" @click="removeCarouselItem(index)" v-if="index !== 0">
									<Close />
								</el-icon>
							</div>

							<div class="card-body">
								<upload-img v-model:imageUrl="item.imgUrl">
									<template #empty>
										<el-icon class="add-icon"><Plus /></el-icon>
										<span>请上传轮播图</span>
									</template>
								</upload-img>

								<div class="link-input">
									<el-select style="width: 100%" v-model="item.link" placeholder="请选择 产品">
										<el-option
											v-for="item in sysProduct"
											:key="item.id"
											:label="`${item.categoryName} — ${item.productName} — ${item.model} — ${item.brand}`"
											:value="item.id"
										/>
									</el-select>
								</div>
							</div>
						</div>

						<div class="add-card" @click="addCarouselItem">
							<el-icon class="add-icon"><Plus /></el-icon>
							<span class="add-text">添加轮播图</span>
						</div>
					</div>
				</el-form-item>
			</el-card>

			<el-card>
				<template #header>
					<div class="card-header">
						<span>产品设置</span>
					</div>
				</template>
				<el-form-item label="产品分类" prop="instrumentCategory">
					<el-select
						v-model="formData.instrumentCategory"
						multiple
						collapse-tags
						collapse-tags-tooltip
						:max-collapse-tags="4"
						placeholder="请选择 产品分类"
					>
						<el-option v-for="item in productTypeData" :key="item.id" :label="item.categoryName" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="新产品" prop="newProduct" v-if="false">
					<el-select v-model="formData.newProduct" placeholder="请选择 新产品">
						<el-option
							v-for="item in sysProduct"
							:key="item.id"
							:label="`${item.categoryName} — ${item.productName} — ${item.model} — ${item.brand}`"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="主要产品" prop="mainProduct" v-if="false">
					<el-select v-model="formData.mainProduct" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="4" placeholder="请选择 主要产品">
						<el-option
							v-for="item in sysProduct"
							:key="item.id"
							:label="`${item.categoryName} — ${item.productName} — ${item.model} — ${item.brand}`"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="热门产品" prop="hotProduct">
					<el-select v-model="formData.hotProduct" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="4" placeholder="请选择 热门产品">
						<el-option v-for="item in productTypeData" :key="item.id" :label="item.categoryName" :value="item.id" />
					</el-select>
				</el-form-item>
			</el-card>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from 'vue';

import { ElMessage } from 'element-plus';
import { addObj, putObj, fetchList } from '/@/api/qytest/sysHomeConfig';
import { getProductCategory } from '/@/api/qytest/sysProductCategory';
import { getsysProduct } from '/@/api/qytest/sysProduct';
import { useMessage } from '/@/hooks/message';
// 定义变量内容
const dataFormRef = ref();
const loading = ref(false);
// 提交表单数据
const formData = reactive({
	id: '',
	carousel: [{ imgUrl: '', link: '' }],
	instrumentCategory: [], //产品分类
	newProduct: '', //新产品
	mainProduct: [], //主要产品
	hotProduct: [], //热门产品
});
const productTypeData = ref([]);
const sysProduct = ref([]);
// 定义校验规则
const rules = reactive({
	carousel: [
		{
			required: true,
			validator: (rule: any, value: any, callback: any) => {
				const flag = value.every((item: any) => item.imgUrl !== '' && item.link !== '');
				if (!flag) {
					callback(new Error('轮播图必须上传图片.选择链接产品'));
				} else {
					callback();
				}
			},
			trigger: 'change',
		},
	],
	instrumentCategory: [
		{
			required: true,
			validator: (rule: any, value: any, callback: any) => {
				if (!value || value.length !== 6) {
					callback(new Error('请选择6个产品分类'));
				} else {
					callback();
				}
			},
			trigger: 'change',
		},
	],
	newProduct: [{ required: true, message: '请选择新产品', trigger: 'change' }],
	mainProduct: [{ required: true, message: '请选择主要产品', trigger: 'change' }],
	hotProduct: [{ required: true, message: '请选择热门产品', trigger: 'change' }],
});
// 添加轮播图项
const addCarouselItem = () => {
	formData.carousel.push({ imgUrl: '', link: '' });
};

// 删除轮播图项
const removeCarouselItem = (index: number) => {
	formData.carousel.splice(index, 1);
};
const getProductTypeData = () => {
	loading.value = true;
	getProductCategory({ current: -1 })
		.then((res: any) => {
			productTypeData.value = res.data.records || [];
		})
		.finally(() => {
			loading.value = false;
		});
};
const getsysProductList = () => {
	loading.value = true;
	getsysProduct({ current: -1 })
		.then((res: any) => {
			sysProduct.value = res.data.records || [];
		})
		.finally(() => {
			loading.value = false;
		});
};
// 初始化始数据
const init = () => {
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	loading.value = true;
	fetchList({ current: -1 })
		.then((res: any) => {
			const data = res.data.records || [];
			if (data && data.length) {
				const form = data[0];
				Object.assign(formData, {
					...form,
					carousel: JSON.parse(form.carousel),
					hotProduct: form.hotProduct.split(','),
					mainProduct: form.mainProduct.split(','),
					instrumentCategory: form.instrumentCategory.split(','),
				});
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

// 提交表单
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return ElMessage.error('请填写所有必填字段');

	try {
		loading.value = true;
		const data = {
			...formData,
			carousel: JSON.stringify(formData.carousel),
			hotProduct: formData.hotProduct.join(','),
			mainProduct: formData.mainProduct.join(','),
			instrumentCategory: formData.instrumentCategory.join(','),
		};
		formData.id ? await putObj(data) : await addObj(data);
		useMessage().success(formData.id ? '修改成功' : '添加成功');
	} catch (err: any) {
	} finally {
		loading.value = false;
	}
};
onMounted(async () => {
	await getProductTypeData();
	await getsysProductList();
	await init();
});
</script>

<style scoped lang="scss">
.layout-padding {
	overflow: auto;
}
.el-input,
.el-select {
	width: 60%;
}
.el-card {
	margin-bottom: 12px;
}
.button-box {
	text-align: center;
}

$primary-color: #409eff;
$danger-color: #f56c6c;
$border-color: #dcdfe6;
$border-radius: 8px;
$box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
$card-width: 183px;

.carousel-list {
	display: flex;
	gap: 16px;
	overflow-x: auto;
	padding-bottom: 6px;
	width: 100%;
	.carousel-card {
		background: white;
		border-radius: $border-radius;
		box-shadow: $box-shadow;
		padding: 16px;
		transition: all 0.3s ease;
		border: 1px solid $border-color;
		display: flex;
		flex-direction: column;
		.el-select {
			min-width: 144px;
		}

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 8px;
			padding-bottom: 8px;
			border-bottom: 1px solid #f1f5f9;

			.card-index {
				font-weight: 500;
				color: #334155;
			}

			.delete-btn {
				color: #94a3b8;
				cursor: pointer;
				font-size: 16px;
				transition: all 0.2s;

				&:hover {
					color: $danger-color;
					transform: scale(1.1);
				}
			}
		}

		.card-body {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 8px;

			.link-input {
				width: 150px;

				:deep(.el-input-group__prepend) {
					background-color: #f5f7fa;
				}
			}
		}
	}

	.add-card {
		flex: 0 0 $card-width;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: white;
		border-radius: $border-radius;
		border: 1px dashed #cbd5e1;
		cursor: pointer;
		transition: all 0.3s ease;
		color: #94a3b8;

		&:hover {
			border-color: $primary-color;
			color: $primary-color;

			.add-icon {
				transform: scale(1.1);
			}
		}

		.add-icon {
			font-size: 32px;
			margin-bottom: 8px;
			transition: all 0.2s;
		}

		.add-text {
			font-size: 14px;
		}
	}
}
</style>
